package loginloglogic

import (
	"context"
	"time"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/mssola/user_agent"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddLoginLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLoginLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLoginLogLogic {
	return &AddLoginLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLoginLogLogic) AddLoginLog(in *syspb.AddLoginLogReq) (*syspb.AddLoginLogResp, error) {
	if in.GetUserName() == "" || in.GetUserAgent() == "" || in.GetIp() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增登录日志：参数缺失"),
			tool.GetErrMsgFormat("insert loginLog"), "params is not existed", in)
	}

	ua := user_agent.New(in.GetUserAgent())
	browser, _ := ua.Browser()

	// 构建实体
	data := &model.SysLoginLog{
		LoginName:     in.GetUserName(),
		Ipaddr:        in.GetIp(),
		LoginLocation: tool.GetCityByIp(in.GetIp()),
		Browser:       browser,
		Os:            ua.OS(),
		Status:        in.GetStatus(),
		Msg:           in.GetMsg(),
		LoginTime:     time.Now(),
		Module:        in.GetModule(),
		CreateUser:    in.GetCreateUser(),
		UpdateUser:    in.GetUpdateUser(),
	}

	// 保存
	_, err := l.svcCtx.SysLoginLogModel.InsertEx(l.ctx, nil, []*model.SysLoginLog{data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError),
			tool.GetErrMsgFormat("insert loginLog"), err, in)
	}

	return &syspb.AddLoginLogResp{}, nil
}
